package com.baidu.iit.pxp.listener;

import com.baidu.iit.pvm.ActivityException;
import com.baidu.iit.pvm.ActivityIllegalArgumentException;
import com.baidu.iit.pxp.delegate.ClassDelegate;
import com.baidu.iit.pxp.delegate.Expression;
import com.baidu.iit.pxp.invocation.TaskListenerInvocation;
import com.baidu.iit.pxp.model.DelegateTask;
import com.baidu.iit.pxp.model.FieldDeclaration;

import java.util.List;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 下午3:47
 */
public class DelegateExpressionTaskListener implements TaskListener {

    protected Expression expression;
    private final List<FieldDeclaration> fieldDeclarations;

    public DelegateExpressionTaskListener(Expression expression, List<FieldDeclaration> fieldDeclarations) {
        this.expression = expression;
        this.fieldDeclarations = fieldDeclarations;
    }

    public void notify(DelegateTask delegateTask) {
        Object delegate = expression.getValue(delegateTask.getExecution());
        ClassDelegate.applyFieldDeclaration(fieldDeclarations, delegate);

        if (delegate instanceof TaskListener) {
            try {
                TaskListenerInvocation invocation = new TaskListenerInvocation((TaskListener) delegate, delegateTask);
                invocation.proceed();
            } catch (Exception e) {
                throw new ActivityException("Exception while invoking TaskListener: " + e.getMessage(), e);
            }
        } else {
            throw new ActivityIllegalArgumentException("Delegate expression " + expression
                    + " did not resolve to an implementation of " + TaskListener.class);
        }
    }


    public String getExpressionText() {
        return expression.getExpressionText();
    }

}
